<?php 
class Cache { 
    private $cache_path;//path for the cache 
    private $cache_expire;//seconds that the cache expires 
      
    //cache constructor, optional expiring time and cache path 
    public function __construct($exp_time=3600,$path="./protected/cache/"){ 
        $this->cache_expire=$exp_time; 
        $this->cache_path=$path; 
    } 
      
    //returns the filename for the cache 
    private function fileName($key){
        $key = md5($key);
        return $this->cache_path.$key.'.php'; 
        // return $this->cache_path.md5($key); 
    } 
      
    //creates new cache files with the given data, $key== name of the cache, data the info/values to store 
    public function set($key, $data, $exp_time=3600){ 
        $values = serialize($data); 
        $values   = "<?php\n//" . sprintf('%012d', $exp_time) . "\n exit();?>\n" . $values;
        $filename = $this->fileName($key); 
        $result = file_put_contents($filename, $values);
        if ($result){
            return true;
        } 
        else return false; 
    } 
      
    //returns cache for the given key 
    public function get($key){ 
        $filename = $this->fileName($key); 
        if (!file_exists($filename) || !is_readable($filename)){//can't read the cache 
            return false; 
        }
        $content = file_get_contents($filename);
        $expire = (int) substr($content, 8, 12);
        if (0 != $expire && time() > filemtime($filename) + $expire) {
            return false;
        }
        $content = substr($content, 32);
        if ($content){
            return unserialize($content);
        }else{
            return false; 
        } 
    } 

    //returns cache for the given key 
    public function del($key){ 
        $filename = $this->fileName($key); 
        if (!file_exists($filename) || !is_readable($filename)){//can't read the cache 
            return false; 
        }
        if ( @unlink($filename) ) {//cache for the key not expired 
            return true;//return the values 
        } 
        else return false;//was expired you need to create new 
    } 
} 